package tech.wetech.admin3.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import tech.wetech.admin3.sys.repository.AooAnotherMeRepository;
import tech.wetech.admin3.sys.repository.AooAnotherSomeoneRepository;
import tech.wetech.admin3.sys.repository.AooVirtualManRepository;
import tech.wetech.admin3.sys.service.AooCountService;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
//@AllArgsConstructor // 这个注解会自动生成一个包含所有成员变量的构造函数。在这个构造函数中，Config类型的config变量可以被Spring自动注入，但是String类型的description和orderAmount变量无法被Spring自动注入，因为它们是基本类型。改为只包含Config的自定义构造函数。
@RequestMapping("/alipay/easy")
public class EasyPayController {
  private final Config config;
  @Autowired
  private AooAnotherMeRepository anotherMeRepository;
  @Autowired
  private AooAnotherSomeoneRepository smoeoneRepository;
  @Autowired
  private AooVirtualManRepository virtualManRepository;
  @Autowired
  private AooCountService countService;

  @Value("${order.description}")
  private String description;

  @Value("${order.orderAmountAli}")
  private String orderAmountAli;

  public EasyPayController(Config config) {
    this.config = config;
  }

  @PostMapping("/create_order")
  public Map<String, String> createOrder(@RequestParam("out_trade_no") String out_trade_no) throws Exception {
    Map res = new HashMap<>();

    // 设置参数,验签
    Factory.setOptions(config);
    // 调用支付宝当面付预下单接口
//    System.out.println("description---" + description);
    AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace().preCreate(description, out_trade_no, orderAmountAli);

    String httpBody = response.getHttpBody();
    log.info("支付宝预下单接口响应：" + httpBody);
    JSONObject jsonObject = JSONObject.parseObject(httpBody);
    JSONObject alipay_trade_precreate_response = jsonObject.getJSONObject("alipay_trade_precreate_response");
    if (response.getCode().equals("10000")) {
      String qrCodeUrl = alipay_trade_precreate_response.getString("qr_code");
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      QrCodeUtil.generate(qrCodeUrl, 300, 300, "png", outputStream);
      String qrCodeBase64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
      res.put("code", "success");
      res.put("out_trade_no", alipay_trade_precreate_response.getString("out_trade_no"));
      res.put("qr_code", qrCodeBase64);
      return res;
    } else {
      res = alipay_trade_precreate_response.toJavaObject(Map.class);
      return res;
    }

  }

  @PostMapping("/notify")
  public String notify(HttpServletRequest request) {
    String out_trade_no = request.getParameter("out_trade_no");

    // 更新订单状态paid，业务逻辑
    countService.updateOrder(out_trade_no);
    log.info("(支付宝)支付成功通知..." + request);
    log.info("订单(%s)已更新：{}", out_trade_no);

    return "success";
  }

  @GetMapping("/query_order")
  public String queryOrder(@RequestParam("out_trade_no") String out_trade_no) throws Exception {
    Factory.setOptions(config);
    AlipayTradeQueryResponse response = Factory.Payment.Common().query(out_trade_no);
    JSONObject jsonObject = JSONObject.parseObject(response.getHttpBody());
    log.info("支付宝订单查询接口响应：" + jsonObject);

    return response.getHttpBody();
  }

}
